<template>
  <div class="sample-info-query">
    <!-- 顶部标题和操作区 -->
    <div class="header">
      <div class="title-wrapper">
        <h1 class="device-name">{{ deviceName }}</h1>
        <span class="subtitle">设备数据统计</span>
      </div>
      <div class="actions">
        <el-button @click="refreshData" type="primary" plain>
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <div class="metrics-row">
      <el-card shadow="hover" class="metric-card">
        <div class="metric-content">
          <div class="metric-icon">
            <el-icon color="#409EFF" :size="24">
              <DocumentChecked/>
            </el-icon>
          </div>
          <div class="metric-value">{{ metrics.totalTests }}</div>
          <div class="metric-title">总体检测批次</div>
        </div>
      </el-card>

      <el-card shadow="hover" class="metric-card">
        <div class="metric-content">
          <div class="metric-icon">
            <el-icon color="#67C23A" :size="24">
              <CircleCheckFilled/>
            </el-icon>
          </div>
          <div class="metric-value">{{ metrics.totalPassRate }}%</div>
          <div class="metric-title">总体合格率</div>
        </div>
      </el-card>

      <el-card shadow="hover" class="metric-card">
        <div class="metric-content">
          <div class="metric-icon">
            <el-icon color="#E6A23C" :size="24">
              <Calendar/>
            </el-icon>
          </div>
          <div class="metric-value">{{ metrics.todayBatches }}</div>
          <div class="metric-title">今日检测批次</div>
        </div>
      </el-card>

      <el-card shadow="hover" class="metric-card">
        <div class="metric-content">
          <div class="metric-icon">
            <el-icon color="#F56C6C" :size="24">
              <Warning/>
            </el-icon>
          </div>
          <div class="metric-value">{{ metrics.todayFailedBatches }}</div>
          <div class="metric-title">今日不合格批次</div>
        </div>
      </el-card>
    </div>

    <!-- 短期趋势图表 -->
    <el-card shadow="hover" class="chart-card">
      <template #header>
        <div class="card-header">
          <span>短期检测趋势</span>
          <el-radio-group v-model="shortTermRange" size="small" @change="updateShortTermChart">
            <el-radio-button label="7">近7天</el-radio-button>
            <el-radio-button label="30">近30天</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div ref="shortTermChart" class="chart-container"></div>
    </el-card>

    <!-- 长期趋势图表 -->
    <div class="content-row">
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="card-header">
            <span>月度检测趋势</span>
          </div>
        </template>
        <div ref="monthTrendChart" class="chart-container"></div>
      </el-card>

      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="card-header">
            <span>年度检测趋势</span>
          </div>
        </template>
        <div ref="yearTrendChart" class="chart-container"></div>
      </el-card>
    </div>

    <!-- 项目分布和排行 -->
    <div class="content-row">
      <el-card shadow="hover" class="chart-card">
        <template #header>
          <div class="card-header">
            <span>项目检测分布</span>
          </div>
        </template>
        <div ref="projectChart" class="chart-container"></div>
      </el-card>

      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="card-header">
            <span>检测项目排行</span>
          </div>
        </template>
        <el-table :data="projectRanking" stripe style="width: 100%">
          <el-table-column prop="rank" label="排名" width="80" align="center">
            <template #default="{ $index }">
              <el-tag :type="getRankTagType($index + 1)">
                {{ $index + 1 }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="projectName" label="项目名称"/>
          <el-table-column prop="testCount" label="检测次数" width="120" align="center"/>
          <el-table-column prop="passRate" label="合格率" width="120" align="center">
            <template #default="{ row }">
              <el-progress
                  :percentage="row.passRate"
                  :color="row.passRate > 90 ? '#67C23A' : row.passRate > 70 ? '#E6A23C' : '#F56C6C'"
                  :show-text="false"
              />
              <span style="margin-left: 8px">{{ row.passRate }}%</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- 详细数据表格 -->
    <el-card shadow="hover" class="full-width-card">
      <template #header>
        <div class="card-header">
          <span>检测数据明细</span>
          <div class="table-actions">
            <el-input
                v-model="tableSearch"
                placeholder="搜索项目/样品"
                clearable
                style="width: 200px"
                @clear="handleSearchClear"
            >
              <template #prefix>
                <el-icon>
                  <Search/>
                </el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>
      <el-table
          :data="filteredTableData"
          stripe
          style="width: 100%"
          v-loading="loading.table"
          @sort-change="handleSortChange"
          :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
      >
        <!-- 固定宽度的关键字段 -->
        <el-table-column
            prop="projectId"
            label="检测编号"
            width="140"
            align="center"
            sortable
            :show-overflow-tooltip="true"
        />

        <!-- 弹性宽度的主要信息 -->
        <el-table-column
            prop="projectName"
            label="项目名称"
            min-width="150"
            align="center"
            sortable
            :show-overflow-tooltip="true"
        />

        <el-table-column
            prop="sampleName"
            label="样品名称"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
        />

        <!-- 日期类固定宽度 -->
        <el-table-column
            prop="testDate"
            label="检测日期"
            width="150"
            align="center"
            sortable
        />

        <!-- 人员信息适当宽度 -->
        <el-table-column
            prop="testPerson"
            label="检测人员"
            width="150"
            align="center"
            :show-overflow-tooltip="true"
        />

        <!-- 数值类字段固定宽度 -->
        <el-table-column
            prop="testValue"
            label="检测值"
            width="150"
            align="center"
            sortable
        >
          <template #default="{ row }">
            <span class="value-display">{{ row.testValue }}</span>
            <span class="unit">{{ row.unit }}</span>
          </template>
        </el-table-column>

        <!-- 结果状态标签固定宽度 -->
        <el-table-column
            prop="result"
            label="检测结果"
            width="150"
            align="center"
        >
          <template #default="{ row }">
            <el-tag
                :type="getResultTagType(row.result)"
                size="small"
                class="status-tag"
            >
              {{ row.result }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 合格性标签固定宽度 -->
        <el-table-column
            prop="quality"
            label="合格性"
            width="150"
            align="center"
        >
          <template #default="{ row }">
            <el-tag
                :type="row.quality  === '合格' ? 'success' : 'danger'"
                size="small"
                class="quality-tag"
            >
              {{ row.quality || '--' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作列固定宽度 -->
        <el-table-column
            label="操作"
            width="150"
            align="center"
            fixed="right"
        >
          <template #default="{ row }">
            <el-button
                type="primary"
                link
                size="small"
                @click="showDetail(row)"
            >
              详情
            </el-button>
            <el-button
                v-if="true"
                type="primary"
                link
                size="small"
                @click="editItem(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <ResultDetailDialog
        v-model="detailDialogVisible"
        :detail-data="currentDetail"
    />
  </div>
</template>

<script setup>
import {ref, onMounted, computed, watch, onUnmounted} from 'vue'
import {
  Refresh, Calendar, Warning, Search,
  DocumentChecked, CircleCheckFilled
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import ResultDetailDialog from "~/layout/components/ResultDetailDialog.vue";
import {getUserResults} from "~/api/results_man.js";
import {formatDate} from "~/utils/timeUtils.js";
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";
import {DEVICE_MENU_ITEMS} from "~/constants.js";
import {foodSafetyDetectionData} from "~/api/mock/data.js";

// 设备名称
const route = useRoute();

// 获取当前设备类型
const deviceType = computed(() => {
  return typeof route.query.type === 'string' ? route.query.type : ''
})

// 根据 type 获取设备名称
const deviceName = computed(() => {
  const matchedDevice = DEVICE_MENU_ITEMS.find(
      item => item.type === deviceType.value
  )
  return matchedDevice?.name || ''
})

// 关键指标数据
const metrics = ref({
  totalTests: 0,
  totalPassRate: 0,
  todayBatches: 0,
  todayFailedBatches: 0
})

// 图表相关
const shortTermRange = ref('7') // 7/30/180
const shortTermChart = ref(null)
const monthTrendChart = ref(null)
const yearTrendChart = ref(null)
const projectChart = ref(null)
let shortTermChartInstance = null
let monthTrendChartInstance = null
let yearTrendChartInstance = null
let projectChartInstance = null

// 项目排行数据
const projectRanking = ref([])

// 表格数据相关
const allTableData = ref([])
const tableSearch = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = computed(() => allTableData.value.length)
const loading = ref({table: false})

// 详情弹窗
const detailDialogVisible = ref(false)
const currentDetail = ref({})

// 计算属性
const filteredTableData = computed(() => {
  let data = [...allTableData.value]

// 搜索过滤
  if (tableSearch.value) {
    const search = tableSearch.value.toLowerCase()
    data = data.filter(item =>
        item.projectName.toLowerCase().includes(search) ||
        item.sampleName.toLowerCase().includes(search)
    )
  }

// 分页
  const start = (currentPage.value - 1) * pageSize.value
  return data.slice(start, start + pageSize.value)
})

// 获取表格数据
const fetchTableData = async () => {
  try {
    console.log('获取检测结果列表数据')
    loading.value.table = true;
// const resultsRes = await getUserResults();
    const resultsRes = foodSafetyDetectionData; // mock数据

    if (resultsRes.code === 10000) {
      allTableData.value = resultsRes.data.map(item => ({
        projectId: item.TestResultId,
        projectName: item.ProjectName,
        sampleName: item.SampleName,
        testDate: formatDate(item.TestDate),
        testPerson: item.TestPerson,
        testValue: item.TcValue,
        unit: item.Unit,
        result: item.TestResult,
        quality: item.Quality
      }));

// 更新统计数据
      updateMetrics(resultsRes.data);
      updateProjectRanking(resultsRes.data);
      updateShortTermChart();
      updateMonthTrendChart();
      updateYearTrendChart();
    }
  } catch (error) {
    console.error(' 获取检测结果列表数据失败', error);
    ElMessage.error(' 获取检测数据失败');
  } finally {
    loading.value.table = false;
  }
};

// 更新关键指标数据
const updateMetrics = (data) => {
// 获取今天日期
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const todayKey = formatDateKey(today);

// 统计数据
  const totalTests = data.length;
  const totalPass = data.filter(item => item.Quality === '合格').length;
  const totalPassRate = totalTests > 0 ? Math.round((totalPass / totalTests) * 100) : 0;

// 今日数据
  const todayData = data.filter(item => {
    const itemDate = new Date(item.TestDate);
    return formatDateKey(itemDate) === todayKey;
  });
  const todayBatches = todayData.length;
  const todayFailedBatches = todayData.filter(item => item.Quality !== '合格').length;

// 更新指标
  metrics.value = {
    totalTests,
    totalPassRate,
    todayBatches,
    todayFailedBatches
  };
};

// 更新项目排行
const updateProjectRanking = (data) => {
// 按项目分组统计
  const projectStats = data.reduce((acc, item) => {
    if (!acc[item.ProjectName]) {
      acc[item.ProjectName] = {
        testCount: 0,
        passCount: 0
      };
    }
    acc[item.ProjectName].testCount++;
    if (item.Quality === '合格') {
      acc[item.ProjectName].passCount++;
    }
    return acc;
  }, {});

// 转换为数组并计算合格率
  projectRanking.value = Object.entries(projectStats)
      .map(([projectName, stats]) => ({
        projectName,
        testCount: stats.testCount,
        passRate: Math.round((stats.passCount / stats.testCount) * 100)
      }))
      .sort((a, b) => b.testCount - a.testCount);

// 更新饼图数据
  updateProjectChart();
};

// 更新短期趋势图表
const updateShortTermChart = () => {
  if (!shortTermChartInstance || !allTableData.value.length) return;

  const days = parseInt(shortTermRange.value);
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - days);

// 生成日期范围
  const dateRange = [];
  for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
    dateRange.push(formatDateKey(new Date(d)));
  }

// 统计数据
  const chartData = {};
  dateRange.forEach(date => {
    chartData[date] = {total: 0, pass: 0, abnormal: 0};
  });

  allTableData.value.forEach(item => {
    const date = formatDateKey(new Date(item.testDate));
    if (chartData[date] !== undefined) {
      chartData[date].total++;
      if (item.quality === '合格') chartData[date].pass++;
      if (item.result === '阳性') chartData[date].abnormal++;
    }
  });

// 准备图表数据
  const dates = dateRange.map(d => d.split('-').slice(1).join('-'));
  const totalData = dateRange.map(date => chartData[date].total);
  const passRateData = dateRange.map(date =>
      chartData[date].total > 0 ? Math.round((chartData[date].pass / chartData[date].total) * 100) : 0
  );
  const abnormalData = dateRange.map(date => chartData[date].abnormal);

  shortTermChartInstance.setOption({
    xAxis: {
      data: dates
    },
    series: [
      {data: totalData},
      {data: passRateData},
      {data: abnormalData}
    ]
  });
};

// 更新月度趋势图表
const updateMonthTrendChart = () => {
  if (!monthTrendChartInstance || !allTableData.value.length) return;

// 按月份统计
  const monthStats = {};
  allTableData.value.forEach(item => {
    const date = new Date(item.testDate);
    const monthKey = `${date.getFullYear()}-${date.getMonth() + 1}`;

    if (!monthStats[monthKey]) {
      monthStats[monthKey] = {total: 0, pass: 0};
    }

    monthStats[monthKey].total++;
    if (item.quality === '合格') monthStats[monthKey].pass++;
  });

// 排序并准备数据
  const sortedMonths = Object.keys(monthStats).sort();
  const months = sortedMonths.map(m => m.replace('-', '年') + '月');
  const totalData = sortedMonths.map(m => monthStats[m].total);
  const passRateData = sortedMonths.map(m =>
      monthStats[m].total > 0 ? Math.round((monthStats[m].pass / monthStats[m].total) * 100) : 0
  );

  monthTrendChartInstance.setOption({
    xAxis: {
      data: months
    },
    series: [
      {data: totalData},
      {data: passRateData}
    ]
  });
};

// 更新年度趋势图表
const updateYearTrendChart = () => {
  if (!yearTrendChartInstance || !allTableData.value.length) return;

// 按年份统计
  const yearStats = {};
  allTableData.value.forEach(item => {
    const date = new Date(item.testDate);
    const yearKey = date.getFullYear().toString();

    if (!yearStats[yearKey]) {
      yearStats[yearKey] = {total: 0, pass: 0};
    }

    yearStats[yearKey].total++;
    if (item.quality === '合格') yearStats[yearKey].pass++;
  });

// 排序并准备数据
  const sortedYears = Object.keys(yearStats).sort();
  const years = sortedYears.map(y => y + '年');
  const totalData = sortedYears.map(y => yearStats[y].total);
  const passRateData = sortedYears.map(y =>
      yearStats[y].total > 0 ? Math.round((yearStats[y].pass / yearStats[y].total) * 100) : 0
  );

  yearTrendChartInstance.setOption({
    xAxis: {
      data: years
    },
    series: [
      {data: totalData},
      {data: passRateData}
    ]
  });
};

// 更新项目分布图表
const updateProjectChart = () => {
  if (!projectChartInstance || !projectRanking.value.length) return;

  const chartData = projectRanking.value.slice(0, 10).map(item => ({
    value: item.testCount,
    name: item.projectName
  }));

  projectChartInstance.setOption({
    series: [{
      data: chartData
    }]
  });
};

// 初始化短期趋势图表
const initShortTermChart = () => {
  shortTermChartInstance = echarts.init(shortTermChart.value);
  shortTermChartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: function (params) {
        let result = `<div style="font-weight:bold;margin-bottom:5px">${params[0].axisValue}</div>`;
        params.forEach(item => {
          result += `
<div style="display:flex;align-items:center;margin:3px 0">
<span style="display:inline-block;width:10px;height:10px;background:${item.color};margin-right:5px"></span>
${item.seriesName}: <strong>${item.value}${item.seriesIndex === 1 ? '%' : ''}</strong>
</div>`;
        });
        return result;
      }
    },
    legend: {
      data: ['检测总量', '合格率', '不合格数量'],
      bottom: 0,
      itemWidth: 12,
      itemHeight: 12
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '检测数量',
        min: 0,
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '合格率(%)',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      }
    ],
    series: [
      {
        name: '检测总量',
        type: 'bar',
        barWidth: '30%',
        data: [],
        itemStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '合格率',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [],
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#67C23A'
        },
        lineStyle: {
          width: 3
        }
      },
      {
        name: '不合格数量',
        type: 'bar',
        barWidth: '30%',
        data: [],
        itemStyle: {
          color: '#EE6666'
        }
      }
    ]
  });
};

// 初始化月度趋势图表
const initMonthTrendChart = () => {
  monthTrendChartInstance = echarts.init(monthTrendChart.value);
  monthTrendChartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['检测总量', '合格率'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        interval: 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '检测数量',
        min: 0
      },
      {
        type: 'value',
        name: '合格率(%)',
        min: 0,
        max: 100
      }
    ],
    series: [
      {
        name: '检测总量',
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#91CC75'
        }
      },
      {
        name: '合格率',
        type: 'line',
        yAxisIndex: 1,
        data: [],
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#EE6666'
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  });
};

// 初始化年度趋势图表
const initYearTrendChart = () => {
  yearTrendChartInstance = echarts.init(yearTrendChart.value);
  yearTrendChartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['检测总量', '合格率'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '检测数量',
        min: 0
      },
      {
        type: 'value',
        name: '合格率(%)',
        min: 0,
        max: 100
      }
    ],
    series: [
      {
        name: '检测总量',
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#73C0DE'
        }
      },
      {
        name: '合格率',
        type: 'line',
        yAxisIndex: 1,
        data: [],
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#FAC858'
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  });
};

// 初始化项目分布图表
const initProjectChart = () => {
  projectChartInstance = echarts.init(projectChart.value);
  projectChartInstance.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '检测项目分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
            formatter: '{b}\n{c} ({d}%)'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ],
    color: [
      '#5470C6', '#91CC75', '#EE6666', '#FAC858',
      '#73C0DE', '#3BA272', '#FC8452', '#9A60B4',
      '#EA7CCC', '#E87C25'
    ]
  });
};

// 格式化日期为YYYY-MM-DD
const formatDateKey = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const refreshData = () => {
  fetchTableData();
  ElMessage.success(' 数据已刷新');
};

const handleSearchClear = () => {
  currentPage.value = 1;
};

const handleSortChange = ({prop, order}) => {
  console.log(' 排序变更:', prop, order);
};

const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handlePageChange = (val) => {
  currentPage.value = val;
};

const showDetail = (row) => {
  currentDetail.value = {...row};
  detailDialogVisible.value = true;
};

const editItem = (row) => {
  currentDetail.value = {...row};
  detailDialogVisible.value = true;
};

const getRankTagType = (rank) => {
  if (rank === 1) return 'danger';
  if (rank === 2) return 'warning';
  if (rank === 3) return 'success';
  return '';
};

const getResultTagType = (result) => {
  switch (result) {
    case '阴性':
      return 'success';
    case '阳性':
      return 'danger';
    default:
      return 'info';
  }
};

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (shortTermChartInstance) shortTermChartInstance.resize();
  if (monthTrendChartInstance) monthTrendChartInstance.resize();
  if (yearTrendChartInstance) yearTrendChartInstance.resize();
  if (projectChartInstance) projectChartInstance.resize();
};

// 生命周期钩子
onMounted(() => {
  initShortTermChart();
  initMonthTrendChart();
  initYearTrendChart();
  initProjectChart();
  fetchTableData();
  window.addEventListener('resize', handleResize);
});

watch(
    [() => allTableData, () => route.query.type],
    ([newAllTableData, newType], [oldAllTableData, oldType]) => {
// 监听 allTableData 变化
      if (newAllTableData !== oldAllTableData) {
        updateShortTermChart();
        updateMonthTrendChart();
        updateYearTrendChart();
        updateProjectChart();
      }

// 监听 route.query.type 变化
      if (newType && newType !== oldType) {
        fetchTableData(newType);
      }
    },
    {immediate: true} // 首次加载也执行
);

// 组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (shortTermChartInstance) shortTermChartInstance.dispose();
  if (monthTrendChartInstance) monthTrendChartInstance.dispose();
  if (yearTrendChartInstance) yearTrendChartInstance.dispose();
  if (projectChartInstance) projectChartInstance.dispose();
});
</script>

<style scoped>
.sample-info-query {
  padding: 24px;
  background-color: #f8fafc;
  min-height: calc(100vh - 64px); /* 减去头部导航高度 */
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 头部区域优化 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding: 16px 0 24px;
  border-bottom: 1px solid rgba(228, 231, 237, 0.5);
  position: relative;
}

.header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100px;
  height: 3px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 3px;
}

.title-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.device-name {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: #1f2d3d;
  line-height: 1.3;
  letter-spacing: 0.5px;
  position: relative;
  padding-left: 16px;
}

.device-name::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 60%;
  background: linear-gradient(to bottom, #409EFF, #67C23A);
  border-radius: 2px;
}

.subtitle {
  font-size: 16px;
  color: #8492a6;
  font-weight: 400;
  margin-left: 16px;
}

/* 指标卡片优化 */
.metrics-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 8px;
}

.metric-card {
  border-radius: 12px;
  border: none;
  height: 100%;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
  position: relative;
  overflow: hidden;
}

.metric-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
}

.metric-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.metric-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 16px;
  position: relative;
}

.metric-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.metric-card:nth-child(2) .metric-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.metric-card:nth-child(3) .metric-icon {
  background: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.metric-card:nth-child(4) .metric-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.metric-value {
  font-size: 36px;
  font-weight: 700;
  color: #1f2d3d;
  margin-bottom: 8px;
  font-family: 'Arial Rounded MT Bold', 'Helvetica Neue', Arial, sans-serif;
}

.metric-title {
  font-size: 15px;
  color: #8492a6;
  letter-spacing: 0.5px;
}

/* 内容区域优化 */
.content-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-card, .table-card, .full-width-card {
  border-radius: 12px;
  border: none;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.chart-card:hover, .table-card:hover, .full-width-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 24px;
  border-bottom: 1px solid rgba(228, 231, 237, 0.6);
}

.card-header span {
  font-size: 17px;
  font-weight: 600;
  color: #1f2d3d;
  position: relative;
  padding-left: 12px;
}

.card-header span::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: linear-gradient(to bottom, #409EFF, #67C23A);
  border-radius: 2px;
}

/* 图表容器优化 */
.chart-container {
  width: 100%;
  height: 380px;
  padding: 10px 20px 20px;
}

/* 表格优化 */
.full-width-card {
  margin-top: 12px;
}

:deep(.el-table) {
  --el-table-border-color: rgba(228, 231, 237, 0.5);
}

:deep(.el-table__header) {
  --el-table-header-text-color: #5e6d82;
  --el-table-header-bg-color: #f8fafc;
}

:deep(.el-table th.el-table__cell) {
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table .el-table__row:hover) {
  background-color: rgba(64, 158, 255, 0.04) !important;
}

/* 分页优化 */
.pagination-wrapper {
  margin-top: 20px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 0 0 12px 12px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid rgba(228, 231, 237, 0.5);
}

/* 数值显示样式 */
.value-display {
  font-weight: 500;
  color: var(--el-color-primary);
}

/* 单位样式 */
.unit {
  margin-left: 4px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

/* 状态标签统一样式 */
.status-tag,
.quality-tag {
  width: 80px;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 1600px) {
  .el-table-column {
    &.projectId {
      width: 120px !important;
    }

    &.projectName {
      min-width: 150px !important;
    }

    &.testDate {
      width: 130px !important;
    }
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .metrics-row {
    grid-template-columns: repeat(2, 1fr);
  }

  .content-row {
    grid-template-columns: 1fr;
  }

  .el-table-column {
    &.testPerson {
      width: 100px !important;
    }

    &.testValue {
      width: 110px !important;
    }

    &.result {
      width: 110px !important;
    }

    &.quality {
      width: 100px !important;
    }
  }
}

@media (max-width: 768px) {
  .metrics-row {
    grid-template-columns: 1fr;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>